import pytest
import json
import pytest
import os

from common.login import login
from config.tools import sep, get_project_path


@pytest.fixture()
def token():
    def _token(user):
        token_json_dir = sep([get_project_path(), "token_dir"])
        if not os.path.exists(token_json_dir):
            os.mkdir(token_json_dir)
        token_json_path = sep([token_json_dir, user + "_token.json"])
        if not os.path.exists(token_json_path):
            print(f"{user}对应的token的Json文件不存在，调用登录接口")
            token = login(user).json()["data"]["token"]
            print(f"写入{user}对应的token的Json文件")
            with open(token_json_path, "w+") as write_token:
                write_token.write(json.dumps({"token": token}))
            return token
        else:
            print(f"{user}对应的token的Json文件已存在，读取Json文件中的token")
            with open(token_json_path, "r") as token_info:
                token = json.loads(token_info.read())
                return token["token"]

    return _token
